const { REQ_PATH, REF_PATH, HOST } = require('./config')
const axios = require('axios')
const router = require('koa-router')()

// 获取默认搜索关键字
router.get('/getDefaultKey', async (ctx, next) => {
  try {
    const url = `${REQ_PATH}/web-interface/search/default`
    const res = await axios.get(url, {
      headers: {
        referer: `${REF_PATH}/search`,
        host: HOST
      },
      params: ctx.request.query
    })
    ctx.response.body = res.data
  } catch (e) {
    ctx.response.body = '出错了'
  }
  await next()
})
// 获取热门搜索关键字
router.get('/getHotKey', async (ctx, next) => {
  try {
    const url = 'https://s.search.bilibili.com/main/hotword'
    const res = await axios.get(url, {
      headers: {
        referer: `${REF_PATH}/search`,
        host: HOST
      },
      params: ctx.request.query
    })
    ctx.response.body = res.data
  } catch (e) {
    ctx.response.body = '出错了'
  }
  await next()
})
// 获取通过输入关键字返回的搜索建议
router.get('/getSuggest', async (ctx, next) => {
  try {
    const url = 'https://s.search.bilibili.com/main/suggest'
    const res = await axios.get(url, {
      headers: {
        referer: `${REF_PATH}/search`,
        host: HOST
      },
      params: ctx.request.query
    })
    ctx.response.body = res.data
  } catch (e) {
    ctx.response.body = '出错了'
  }
  await next()
})

// 获取通过关键字返回的搜索结果
router.get('/getResult', async (ctx, next) => {
  try {
    const url = `${REQ_PATH}/web-interface/search/all/v2`
    const res = await axios.get(url, {
      headers: {
        referer: `${REF_PATH}/search?keyword=${encodeURIComponent(ctx.request.query.keyword)}`,
        host: HOST
      },
      params: ctx.request.query
    })
    ctx.response.body = res.data
  } catch (e) {
    ctx.response.body = '出错了'
  }
  await next()
})

// 获取通过关键字返回的相关的内容
router.get('/byKeyword', async (ctx, next) => {
  try {
    const url = `${REQ_PATH}/web-interface/search/type`
    const res = await axios.get(url, {
      headers: {
        referer: `${REF_PATH}/search?keyword=${encodeURIComponent(ctx.request.query.keyword)}`,
        host: HOST
      },
      params: ctx.request.query
    })
    ctx.response.body = res.data
  } catch (e) {
    ctx.response.body = '出错了'
  }
  await next()
})
module.exports = router
